
M=require("ming_node")
var oss = require('ali-oss');
app=M.server()
app.listen(10000)


config={
  accessKeyId: 'LTAI2KwBDCCOCmgc',
  accessKeySecret: 't8R9LyB6GOdKF04u0VqmhXFYtkxIqA',
  bucket: 'intermaxtech',
  region: 'oss-cn-hangzhou',
  ossPath:'config/plcm-vtc-machine',
}


M.ossBaseUrl="https://intermaxtech.oss-cn-hangzhou.aliyuncs.com/config/plcm-vtc-machine/"
M.rootPath="config/plcm-vtc-machine/"

var client  = oss(config);

async function listOss() {
  client.useBucket(config.bucket);  
  var result =await  client.list({ "prefix":config.ossPath});
  return result.objects.map(u=>u.name.substring(u.name.lastIndexOf('/')+1)).filter(u=>u.trim().length>0)
}


async function updateOss(k,v){  
  let r1 = await client.put(k, Buffer.from(v)); 
  //console.log(r1)
};
  





app.begin((req, res) => {
    console.log("req ", req.url)
    if(req.url=="/"){
      res.redirect("/index.html")
    }
   
})



app.get("/tree",async (req,res)=>{
  let r=  await listOss()
  r=r.map(u=>{return {name:u}})
  console.log(r)
   var data = { "name": "root", "children": r }
   res.send(data)
})


app.get("/getFile",async (req,res)=>{
    res.alreadySend=true
     M.get(M.ossBaseUrl+req.params.file,d=>{
       res.renderHtml(d)
    })
  
})


app.post("/updateFile",async (req,res)=>{
  console.log(req.params,req.body)
  res.alreadySend=true
  await updateOss(M.rootPath+req.params.file,req.body)
  res.send(M.result("ok"))
})

app.get("/getOssBaseUrl",async (req,res)=>{
 
  res.send(M.result(M.ossBaseUrl))
})

